<script setup lang="ts">
import { ref } from 'vue'
import { useUserStore } from '@/stores/userStore'
import { ElMessage } from 'element-plus'
import http from '@/utils/http'
import { useRouter } from 'vue-router'

const router = useRouter()
const userStore = useUserStore()
const form = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: '',
  username: userStore.user?.username || '',
  originalUsername: userStore.user?.username || ''  // 新增原始用户名字段
})
const loading = ref(false)

const handleSubmit = async () => {
  // 先检查表单是否通过验证
  if (!form.value.oldPassword || !form.value.newPassword || !form.value.confirmPassword) {
    ElMessage.warning('请填写完整信息')
    return
  }
  
  if (form.value.newPassword !== form.value.confirmPassword) {
    ElMessage.warning('两次输入的新密码不一致')
    return
  }

  loading.value = true
  try {
    await http.post('/user/profile/', {
      oldPassword: form.value.oldPassword,
      newPassword: form.value.newPassword,
      username: form.value.username,
      originalUsername: form.value.originalUsername  // 传给后端原始用户名
    })
    
    ElMessage.success('修改成功，请重新登录')
    
    // 清除用户状态
    userStore.clearUser()
    router.push('/login')
    
  } catch (error: any) {
    const errorMsg = error.response?.data?.message || '修改失败'
    ElMessage.error(errorMsg)
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <el-card class="profile-card">
    <template #header>
      <div class="card-header">
        <span>修改个人信息</span>
      </div>
    </template>
    <el-form :model="form" label-width="120px">
      <el-form-item label="用户名" prop="username" :rules="[
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
      ]">
        <el-input v-model="form.username" />
      </el-form-item>
      
      <el-form-item label="原密码" prop="oldPassword" :rules="[
        { required: true, message: '请输入原密码', trigger: 'blur' }
      ]">
        <el-input v-model="form.oldPassword" type="password" show-password />
      </el-form-item>
      
      <el-form-item label="新密码" prop="newPassword" :rules="[
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
      ]">
        <el-input v-model="form.newPassword" type="password" show-password />
      </el-form-item>
      
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input v-model="form.confirmPassword" type="password" show-password />
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" @click="handleSubmit" :loading="loading">提交修改</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<style scoped>
.profile-card {
  max-width: 600px;
  margin: 20px auto;
}
</style>